package com.heima.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1. 如果参数都有值-则按照正常登录处理
        if(StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {

            //1.1 判断用户是否存在  select * from ap_user where phone=?
            //ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            ApUser apUser = this.lambdaQuery().eq(ApUser::getPhone, dto.getPhone()).one();
            if(apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }

            //1.2 判断密码是否正确
            String loginPwd =  dto.getPassword(); //登录明文密码
            String dbPwd = apUser.getPassword(); //表中密文密码
            boolean result = BCrypt.checkpw(loginPwd, dbPwd);
            if(!result) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //1.3 判断状态是否正常
            if(apUser.getStatus()) {
                return ResponseResult.errorResult(AppHttpCodeEnum.INVALID_STATUS);
            }

            //1.4 生成用户Token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());

            Map hashMap = new HashedMap();
            hashMap.put("token",token);

            apUser.setPassword("");
            hashMap.put("user",apUser);

            return ResponseResult.okResult(hashMap);
        } else {
            //2. 如果参数无值-则按照游客登录处理
            String token = AppJwtUtil.getToken(0L);

            Map hashMap = new HashedMap();
            hashMap.put("token",token);

            //return ResponseResult.okResult(null);
            return ResponseResult.okResult(hashMap);
        }
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
